package com.hao.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hao.eduservice.entity.EduSubject;
import com.hao.eduservice.entity.excel.SubjectData;
import com.hao.eduservice.entity.subject.OneSubject;
import com.hao.eduservice.entity.subject.TwoSubject;
import com.hao.eduservice.listener.SubjectExcelListener;
import com.hao.eduservice.mapper.EduSubjectMapper;
import com.hao.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hao
 * @since 2020-11-30
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        //一级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EduSubject> list = this.list(wrapper);
        //二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id",0);
        List<EduSubject> list2 = this.list(wrapper2);
        //封装结果
        List<OneSubject> finalList = new ArrayList<>();
        for(EduSubject oneSubject:list){
            OneSubject one = new OneSubject();
            BeanUtils.copyProperties(oneSubject,one);
            List<TwoSubject> finalList2 = new ArrayList<>();
            //二级分类封装到一级
            for(EduSubject twoSubject:list2){
                if(twoSubject.getParentId().equals(one.getId())){
                    TwoSubject two = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,two);
                    finalList2.add(two);
                }
                one.setChildren(finalList2);
            }
            finalList.add(one);
        }
        return finalList;
    }



}
